package com.gesonet.common.utils.json;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Title: Jackson包装类 Desc: JacksonJson简单封装 Date: 13-7-16 下午7:51
 */
public class JacksonJsonMapper {

	private static final Logger log = LoggerFactory.getLogger(JacksonJsonMapper.class);

	static volatile ObjectMapper objectMapper = null;

	/**
	 * 获取唯一的ObjectMapper对象
	 * 
	 * @return
	 */
	public static ObjectMapper getInstance() {
		if (objectMapper == null) {
			synchronized (ObjectMapper.class) {
				if (objectMapper == null) {
					objectMapper = new ObjectMapper();
					objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
				}
			}
		}
		return objectMapper;
	}

	public static String getResultCode(String json) throws Exception {
		JsonNode jsonNode = JacksonJsonMapper.getInstance().readTree(json);
		String resultCode = jsonNode.get("code").getTextValue();
		return resultCode;
	}

	public static JsonNode getData(String json) throws Exception {
		JsonNode jsonNode = JacksonJsonMapper.getInstance().readTree(json);
		JsonNode data = jsonNode.get("data");
		return data;
	}

	public static int getValueAsInt(String json, String filedName) throws Exception {
		JsonNode jsonNode = JacksonJsonMapper.getInstance().readTree(json);
		JsonNode data = jsonNode.get(filedName);
		return data.asInt();
	}

	public static String getValueAsString(String json, String filedName) throws Exception {
		JsonNode jsonNode = JacksonJsonMapper.getInstance().readTree(json);
		JsonNode data = jsonNode.get(filedName);
		return data.asText();
	}

	public static <T> T json2Bean(JsonNode node, Class<T> clazz) {
		try {
			return JacksonJsonMapper.getInstance().readValue(node, clazz);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static <T> List<T> json2List(JsonNode json, Class<T> clazz) {
		List<T> list = new ArrayList<T>();
		if (json == null) {
			return list;
		}
		try {
			for (JsonNode jsonNode : json) {
				T t = json2Bean(jsonNode, clazz);
				list.add(t);
			}
		} catch (Exception e) {
			log.error("json数据不合法：" + json);
			e.printStackTrace();
		}
		return list;
	}


}
